#!/bin/bash
#must run in this dir
#function: auto create new app and action file

echo "please input new app name"
while read app_name
do
    if [ "$app_name" ]
    then
        break
    fi
    echo "please input new app name"
done

echo "please input new action name"
while read action_name
do
    if [ "$action_name" ]
    then
        break
    fi
    echo "please input new action name"
done

current_dir=$(pwd)
#root_dir=`dirname $current_dir`
#root_dir=`dirname $root_dir`
#root_dir=`dirname $root_dir`
root_dir=$current_dir

app_dir=$root_dir/application/apps
scaffold_dir=$root_dir/system/script/scaffold

#$app_name=$1
#$action_name=$2
new_app_path=$app_dir/$app_name
type_names=(controller action view model template)

if [ ! -d $new_app_path ]
then
    mkdir -p $app_dir/$app_name
fi

for type_name in ${type_names[*]}
do
    dirname=$type_name"s"

    #if dir not exists
    if [ ! -d $new_app_path/$dirname ]
    then
        mkdir -p $new_app_path/$dirname
    fi

    filename=$new_app_path/$dirname/$action_name.$type_name.php

    if [ ! -f $filename ]
    then
        cp $scaffold_dir/$dirname/$type_name.php $filename
    else
    	echo -e $filename "is exists\n"
    fi
done


#convert first alpha to upper
app_classname=`echo $app_name|sed 's/\b[a-z]/\U&/g'|sed -e 's#\/#_#g'`
action_classname=`echo $action_name |sed 's/^[a-z]/\U&/'`

#cmd="sed -i s/{\\\$app}/$class_prefix/g" "\`grep -rinl '{\$app}' $new_app_path\`"
#cmd="sed -i \"s/{\\\$app}/$class_prefix/g\" \`grep -rinl '{\$app}' $new_app_path\`"

sed -i "s/{\$app}/$app_classname/g" `grep -rinl '{\$app}' $new_app_path`
sed -i "s/{\$action}/$action_classname/g" `grep -rinl '{\$action}' $new_app_path`

echo done

